#include <string>
#include <iostream>
#include <fstream>

#include <Ice/Ice.h>
#include <sg_ice.h>

using namespace std;
using namespace suggestion;

suggestion::VectorSg loadData(char *path)
{
    suggestion::VectorSg data;
    suggestion::SG data_row;

    ifstream fin(path);

    int MAX_LENGTH = 100;
    char line[MAX_LENGTH];

    string token;
    stringstream iss;
    while (fin.getline(line, MAX_LENGTH))
    {
        iss << line;

        getline(iss, token, '\t');
        data_row.index = atoi(token.c_str());

        getline(iss, token, '\t');
        data_row.text = token;

        iss.clear();

        // put struct into vector
        data.push_back(data_row);
    }
    return data;
}

int main(int argc, char *argv[])
{
    // help
    if (argc < 3){ 
        fprintf (stderr, "Usage: client [user data file] [search string]\n\n");
        fprintf (stderr, "  example: ./client /root/sgserver/data/userdata l\n\n");
        exit(1);
    }

    string query = argv[2];
    // load for test
    suggestion::VectorSg sdData = loadData(argv[1]);
    suggestion::VectorUid uids;

    try {
        Ice::CommunicatorPtr ic = Ice::initialize(argc, argv);
        Ice::ObjectPrx base = ic->stringToProxy("kxSuggestion:tcp -h localhost -p 10000");
        if(!base) {
            throw "can't connect server";
        }
        SuggestPrx sgObj = SuggestPrx::checkedCast(base);
        if(!sgObj) {
            throw "Invalid proxy";
        }
        uids = sgObj->doSearch(query, sdData, 1);
        int uidCount = uids.size();
        cout << "\n==========================================================\n";
        for(int i = 0; i < uidCount; i++) {
            cout << uids[i] << "\t";
        }
        cout << "\n\nCOUNT: " << uidCount;
        cout << "\n==========================================================" << endl;

    } catch(const Ice::Exception &e) {
        cerr << e << endl;
    } catch(const char *msg) {
        cerr << msg << endl;
    }

    return 0;
}
